<script lang="ts" setup>
import defaultIcon from '~/assets/imgs/default_type.png';

export interface GameItem {
  value: string;
  name: string;
  icon: string;
};

const $props = withDefaults(defineProps<{ activeCls?: string }>(), { activeCls: 'text-green font-semibold' });

const emits = defineEmits<{ select: [value: GameItem] }>();

defineSlots<{ default: (props: { active?: GameItem; isShow: boolean }) => any }>();

const appStore = useAppStore();

const showSheet = defineModel<boolean>('show', { default: false });

const activeGame = defineModel<GameItem>('active', { default: void 0 });

const gameList = ref<GameItem[]>([]);

apis.apiGameAll(void 0).then((res) => {
  const allGame = Object.values(res?.game_map ?? []).filter(x => x?.provider_id === 1);
  gameList.value = allGame.map(x => ({ value: x.code, name: x.ename, icon: appStore.joinCdnPath(x.image_icon) }));
  gameList.value.length && !activeGame.value && selectGame(gameList.value?.[0].value);
});

const getBindProps = toRef(() => ({
  options: gameList.value.map(x => ({ ...x, label: x.name, popupClassName: activeGame.value && x.value === activeGame.value?.value ? $props.activeCls : '' })),
  labelInValue: true,
  change: selectGame,
}));

function selectGame(game: string) {
  const i = getBindProps.value.options.filter(i => i.value === game);

  activeGame.value = i[0];
  emits('select', i[0]);
}

function onImageError(e: any) {
  e.target.src = defaultIcon;
}
</script>

<template>
  <div>
    <TAntdTheme component="Select" theme="light">
      <ASelect v-model:value="activeGame" :virtual="false" class="w-full" @change="selectGame">
        <ASelectOption v-for="(i, k) in getBindProps.options" v-bind="i" :key="k">
          <div class="flex-center justify-start gap-2">
            <img :src="!!i.icon ? i.icon : defaultIcon" class="h-4 w-4" @error="onImageError"> {{ i.value }}
          </div>
        </ASelectOption>
      </ASelect>
    </TAntdTheme>

    <slot :active="activeGame" :isShow="showSheet" />
  </div>
</template>
